<script lang="ts" setup>
import { createPropertyAPI, delPropertyAPI, getAllBuildingListAPI, getAllEnterpriseListAPI, getPropertyBudgetAPI, getPropertyListAPI } from '@/apis/property';
import type { Building } from '@/types/building';
import type { Enterprise } from '@/types/enterprise';
import type { Property, PropertyListParams, PropertyParams } from '@/types/property';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';

// 日期数组
const cardDateArr = ref<string[]>([])
// 监听日期变化，收集后端所需的数据
watch(cardDateArr, (val) => {
  if (val) {
    params.value.start = val[0]
    params.value.end = val[1]
  } else {
    params.value.start = ''
    params.value.end = ''
  }
}, { deep: true })
const list = ref<Property[]>([])
const total = ref(0)
const params = ref<PropertyListParams>({
  page: 1,
  pageSize: 10,
  enterpriseName:'',
  start: '',
  end: ''
})
const getList = async () => {

  const res = await getPropertyListAPI(params.value)
  // console.log('res',res)
  list.value = res.data.rows
  total.value = res.data.total
}

getList()

const onSearch = () => {
  params.value.page = 1
  getList()
}
const initAddForm = () => {
  return {
  buildingId: undefined,
  startTime: '',
  endTime: '',
  paymentMethod: 1,
  paymentAmount: undefined,
  enterpriseId: undefined
}
}
// 弹窗相关
const addForm = ref<PropertyParams>(initAddForm())
const addFormRef = ref<FormInstance>()
const addFormRules = ref<FormRules<PropertyParams>>({
  buildingId: [
    { required: true, message: '请选择租赁楼宇', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  paymentMethod: [
    {required: true, message: '请选择付款方式', trigger: 'change'}
  ],
  paymentAmount: [
    { required: true, message: '请输入缴费金额', trigger: 'change' }
  ],
  enterpriseId: [
    { required: true, message: '请选择租户', trigger: 'change' }
  ]
})

const buildingDialogFlag = ref(false)
const submitLoading = ref(false)
const AllEnterpriseList = ref<Enterprise[]>([])
const AllBuildingList = ref<Building[]>([])
const dataArr =  ref<string[]>([])
  watch(dataArr, (val) => {
  if (val) {
    addForm.value.startTime = val[0]
    addForm.value.endTime = val[1]
  } else {
    addForm.value.startTime = ''
    addForm.value.endTime = ''
  }
}, { deep: true })
// 查询所有企业
  const getAllEnterpriseList = async() => {
    const res = await getAllEnterpriseListAPI()
    // console.log('res',res)
    AllEnterpriseList.value = res.data
  }
// 查询所有楼宇
const getAllBuildingList = async() => {
  const res = await getAllBuildingListAPI()
  // console.log('res',res)
  AllBuildingList.value = res.data
}

const onClose = () =>{
  // 重置表单数据
  addForm.value = initAddForm()
  addFormRef.value?.resetFields()
  dataArr.value = []
  buildingDialogFlag.value = false
}
//  提交表单
const onSubmit = async() => {
  // console.log('addForm',addForm.value)
  try {
    if(addForm.value.id){

    }else{
        // 表单验证
      submitLoading.value = true
      await addFormRef.value?.validate()
      await createPropertyAPI(addForm.value)
      ElMessage.success('添加成功')
      getList()
    }
    onClose()
  } catch {
    submitLoading.value = false
  }
}
// 删除账单
const delProperty = async(id: number) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    await delPropertyAPI(id)
    // console.log('res',res)
    ElMessage.success('删除成功')
    getList()
  })
}
const dialogValue = ref(0)
// 新增账单
const onAdd = () => {
  dialogValue.value = 0
  buildingDialogFlag.value = true
  getAllEnterpriseList()
  getAllBuildingList()
}
// 查看账单
const viewProperty = (row: Property) => {
  dialogValue.value = 1
  buildingDialogFlag.value = true
  // console.log('row',row)
  addForm.value = {
    buildingId: row.buildingId,
    startTime: row.startTime,
    endTime: row.endTime,
    paymentMethod: row.paymentMethod as number | undefined,
    paymentAmount: row.paymentAmount,
    enterpriseId: row.enterpriseId,
    enterpriseName: row.enterpriseName,
    buildingName: row.buildingName,
    propertyFeePrice: row.propertyFeePrice,
    createTime: row.createTime,
    id: row.id
  }
}
// 支付金额发请求获取：watch监听addForm,当改变，并且楼宇id和开始结束日期存在时，就发请求获取金额
watch(addForm, async (val: PropertyParams) => {
  // console.log('val',val)
  if(val.buildingId && val.startTime){
    const res = await getPropertyBudgetAPI({
      buildingId: val.buildingId,
      startTime: val.startTime,
      endTime: val.endTime
    })
    // console.log('res',res)
    addForm.value.paymentAmount = res.data
  }
},{deep: true})

// 获取路由参数
const route = useRoute()
const type = route.query.type

// 如果type为workbench，则直接打开添加账单弹窗
if(type === 'workbench'){
  onAdd()
}

</script>

<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">企业名称：</span>
      <el-input clearable placeholder="请输入企业名称" v-model="params.enterpriseName" class="search-main" />
      <span class="search-label">缴费时间：</span>
      <div>
        <el-date-picker 
          v-model="cardDateArr"
          value-format="YYYY-MM-DD" 
          type="daterange" 
          range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" 
        />
      </div>
      <el-button type="primary" class="search-btn" @click="onSearch">查询</el-button>
    </div>
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="onAdd">添加账单</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="billNumber" label="账单编号" />
        <el-table-column prop="enterpriseName" label="企业名称" />
        <el-table-column prop="buildingName" label="租赁楼宇" />
        <el-table-column prop="propertyFeePrice" label="物业费(元/m²)" />
        <el-table-column prop="paymentAmount" label="账单金额(元)" />
        <el-table-column prop="createTime" label="缴费时间" width="180" />
        <el-table-column label="操作" fixed="right">
          <template #default="{row}">
            <el-button size="small" type="primary" link @click="viewProperty(row)">查看</el-button>
            <el-button size="small" type="primary" link @click="delProperty(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container">
      <el-pagination 
      layout="total, prev, pager, next ,sizes, jumper" 
      :total="total" 
      v-model:current-page="params.page" 
      v-model:page-size="params.pageSize"
      @change="getList()"
      />
    </div>
    <el-dialog :title="dialogValue === 0 ? '添加账单' : '查看账单'" width="600px" v-model="buildingDialogFlag" @close="onClose">
      <!-- {{ addForm }} -->
      <div class="form-container" v-if="dialogValue === 0">
        <el-form label-width="100px" label-position="top" :model="addForm" :rules="addFormRules" ref="addFormRef">
          <el-form-item label="选择租户" prop="enterpriseId">
            <el-select v-model="addForm.enterpriseId" placeholder="请选择租户" clearable>
              <el-option
                v-for="item in AllEnterpriseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="addForm.buildingId"  placeholder="请选择租赁楼宇" clearable>
              <el-option
                v-for="item in AllBuildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="缴费周期" prop="startTime">
            <el-date-picker 
              v-model="dataArr"
              value-format="YYYY-MM-DD" 
              type="daterange" 
              range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" 
            />
          </el-form-item>
          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input type="number" v-model="addForm.paymentAmount" disabled></el-input>
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="addForm.paymentMethod" placeholder="请选择支付方式" clearable>
              <el-option label="微信" :value="1"></el-option>
              <el-option label="支付宝" :value="2"></el-option>
              <el-option label="现金" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="info-container" v-else>
        <div>租户名称：{{ addForm.enterpriseName }}</div>
        <div>租赁楼宇：{{ addForm.buildingName }}</div>
        <div>缴费周期：{{ addForm.startTime }}至{{ addForm.endTime }}</div>
        <div>物业费(m/²)：{{ addForm.propertyFeePrice }}</div>
        <div>账单金额(元)：{{ addForm.paymentAmount }}</div>
        <div>支付方式：{{ addForm.paymentMethod === 1 ? '微信支付' : addForm.paymentMethod === 2 ? '支付宝' : '现金' }}</div>
        <div>缴费时间：{{ addForm.createTime }}</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button size="small" @click="onClose">取 消</el-button>
           <el-button size="small" type="primary" @click="onSubmit" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
.info-container{
  display: flex;
  flex-direction: column;
  padding: 20px;
  align-items: start;
  margin-left: 150px;
  gap: 20px;
}
</style>